const Router = require('koa-router')
const router = new Router()
const newsModal = require('../models/News')
const formModal = require('../models/Form')
const news = require('../routes/news')
const newsDetail = require('../routes/newsDetail')
const invsetSearch = require('../routes/investSearch')
const FormData = require('form-data');
const fs = require('fs');
const multiparty = require('koa2-multiparty');

function index ({ router, baseUrl = '' }) {
    router.get(baseUrl + '/', async (ctx, next) => {
        try {
            const reses = await Promise.all([
                newsModal.getList({ pageSize: 8, type: 'NEWS' }),
                newsModal.getList({ pageSize: 8, type: 'INFO' }),
            ]);
            ctx.render('index/index.pug', { news: reses[0], info: reses[1], ssr: true, baseUrl });
        } catch (err) {
            next(err);
        }
    });


    router.post('/user/uploadRawPic', multiparty(), async (ctx, next) => {
        try {
            // console.log(ctx.req.files)
            let file = fs.createReadStream(ctx.req.files.file.path)
            const res = await formModal.upload({ file })
            let json = await res.json();
            // console.log(json);
            await fs.unlink(ctx.req.files.file.path, () => {});
            ctx.response.type = 'json';
            ctx.response.body = json;
        } catch (err) {
            console.log(err)
            next(err);
        }
    });

    router.post(baseUrl + '/admin/add/innovation', multiparty(), async (ctx, next) => {
        try {
            // console.log(ctx.req.body)
            let res = await formModal.addInnovation(ctx.req.body);
            // console.log(res)
            let json = await res.json();
            // console.log(json)
            ctx.response.type = 'json';
            ctx.response.body = json;
        } catch (err) {
            console.log(err)
            next(err);
        }
    });

    router.post(baseUrl + '/admin/add/investment', multiparty(), async (ctx, next) => {
        try {
            // console.log(ctx.req.body)
            let res = await formModal.addInvestment(ctx.req.body);
            // console.log(res)
            let json = await res.json();
            // console.log(json)
            ctx.response.type = 'json';
            ctx.response.body = json;
        } catch (err) {
            console.log(err)
            next(err);
        }
    });

}


module.exports = function (app) {
    const config = {
        router,
        baseUrl: '/shuangchuang'
    }
    index({ ...config });

    news({ ...config, type: 'NEWS', path: '/news', name: '新闻信息' });

    news({ ...config, type: 'INFO', path: '/info', name: '公事信息' });

    newsDetail({ ...config });

    invsetSearch({ ...config, type: 'invest', path: '/invest', name: '投资项目' });

    invsetSearch({ ...config, type: 'pioneering', path: '/pioneering', name: '创业项目' });

    app.use(router.routes()).use(router.allowedMethods());
}
